package com.example.demo.sys.service.annotation;

import com.example.demo.sys.service.UserService;
import com.example.demo.sys.service.bo.UserBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;

@Slf4j
@Component
public class UserValidation<T extends Annotation> implements ConstraintValidator<T, UserBO> {
    @Autowired
    private UserService userService;

    /**
     * 校验用户是否唯一
     * 即判断数据库是否存在当前新用户的信息，如用户名，手机，邮箱
     */
    public static class UniqueUserValidator extends UserValidation<UniqueUser> {
        @Override
        public void initialize(UniqueUser constraintAnnotation) {
            //传入value 值，可以在校验中使用
            log.info("验证用户名是否重复");
        }
    }

    public boolean isValid(UserBO userBO, ConstraintValidatorContext constraintValidatorContext) {
        log.info("uid:" + userBO.getId());
        return userService.checkUsernameUnique(userBO);
    }
}
